import search_view from './../../views/search/index';
var self_select = require('{plus}/select');
var self_date = require('{plus}/calendar')
var events = require('events');
var template = require('template');
var request = require('{pub}/request');
var json = require('{polyfill}/json');
var message = require('{layer}/message');
var placeholder = require('placeholder');
var zTree = require('{pub}/jquery.ztree.all');
var layer = require('layer');
return events({
    companyList:null,
    zTreeObj:null,
    binds:function() {
         if (!Function.prototype.bind) { 
            Function.prototype.bind = function (oThis) {   
                if (typeof this !== "function") {         
                    throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");   
                }   
                var aArgs = Array.prototype.slice.call(arguments, 1),   
                fToBind = this,   
                fNOP = function () {},   
                fBound = function () {   
                    return fToBind.apply(this instanceof fNOP && oThis   
                        ? this   
                        : oThis,   
                        aArgs.concat(Array.prototype.slice.call(arguments)));   
                };   
                fNOP.prototype = this.prototype;   
                fBound.prototype = new fNOP();   
                return fBound;   
            };   
        }   
    },
    events:{
        'click':'hideOpt',
        'click .g-top-view .m-self-select-option .f-self-selbtn':'showOption',
        'click .g-top-view .m-self-select-option .f-self-opt li':'selectedOption',
        'click .g-top-view .m-self-select-date .date-text':'selectDate',
        'click .g-top-view .f-export':'export',
        'click .g-top-view #countryTax':'showTree',
        'click .g-top-view .f-self-ztree':'stopPrag'
    },
    exportParam:null,
    hideOpt:function(e,elem) {
        var className = e.target.className;
        if(className.indexOf('f-self-selbtn') === -1 && className.indexOf('selec-show') === -1 && className.indexOf('select-txt') === -1 && className.indexOf('bd-sin') === -1 && className.indexOf('z-tree')) {
            $('.self-option').css('display','none');
        }
    },
    showOption:function(e,elem) {
        var dom = elem.next('.f-self-opt'),dis = dom.css('display');
        $('.self-option').css('display','none');
        if(dis === 'block'){
            dom.css('display','none')
        } else {
            dom.css('display','block')
        }
    },
    showTree:function() {
        var dis = $('#zTree').css('display'),that = this;
        
        if(dis === 'none') {
            $('#zTree').show();
            
        } else {
            $('#zTree').hide();
        }
    },
    stopPrag:function(e,elem) {
        e.stopPropagation();

    },
    reqCompany:function(e,elem) {
        var flag = false,that = this;
        var setting = {  
            check: {
				enable: true
			},
			data: {
				simpleData: {
					enable: true,
                    idKey:"id",
                    pIdKey:"pId",
                    rootPId:0
				}
			},
            callback:{
                onCheck: that.zTreeOnCheck.bind(this),
                beforeCheck:that.zTreeBeforeCheck
            }
        };
        request.get('/dept/getUserBelongCompanyList',{},function(res){
            if(res.result === 'success') {
                that.companyList = res.data;
                that.companyList[0].open=true
                that.zTreeObj = $.fn.zTree.init($("#zTree"), setting, that.companyList);
            }
        });
    },
    zTreeOnCheck:function(e,r,data) {
        var that = this;
        var checkArr =  that.zTreeObj.getCheckedNodes(true),i,len = checkArr.length,newCompanyArr = [],isChecked,isHalf,level,idStr = [];
        for(i = 0;i<len;i++) {
            isChecked = checkArr[i].getCheckStatus().checked;
            isHalf = checkArr[i].getCheckStatus().half;//true:半选，false：全选
            if(isChecked && !isHalf) {
                newCompanyArr.push({
                    name:checkArr[i].name,
                    id:checkArr[i].id,
                    pid:checkArr[i].pId,
                    level:checkArr[i].level
                });
                idStr.push(checkArr[i].id);
            }
        }
        $('#nationTax').val(idStr.toString())
        if(newCompanyArr.length>1){
            $('#countryTax').val(newCompanyArr[0].name+'...')
        } else if(newCompanyArr.length === 1) {
            $('#countryTax').val(newCompanyArr[0])
        } else {
            $('#countryTax').val('全部')
        }
    },
    zTreeBeforeCheck:function(e,data,r) {
        // console.log(this)
    },
    selectedOption:function(e,elem) {
        var values = elem.data('value');
        var id = elem.data('id');
        elem.parent('.f-self-opt').siblings('.f-self-selbtn').text(values);
        elem.parent('.f-self-opt').siblings('input[type=hidden]').val(id)
    },
    selectDate:function(e,elem) {
        $.calendar({
            target:'#selectDate',
            istwo:true,
            iscope:true,
            yearcount:12,
            joint:'至'
        });
    },
    export:function(e,elem) {
        var funUrl = elem.data('fun'),funType = elem.data('type');
        var url = this.exportParam[funUrl];
        var tbData = $('#tfixData'),
            arrInput = tbData.find('i.checked'),i,len = arrInput.length,selectids=[];
        if(len) {
            for(i=0;i<len;i++){
                selectids.push(arrInput.eq(i).data('val'))
            }
        }
        if(funType) {
            if(selectids.length === 1) {
                this.showInfo(selectids,url)
            } else {
                message('error','请选择一行数据')
            }
            return;
        }
        newSelectids = selectids.toString();
        //查询条件参数获取
        var formParam = $('#seldctForm').serializeArray(),i,formLen = formParam.length,newObj = {};
        for(i=0;i<formLen;i++) {
            newObj[formParam[i].name]=formParam[i].value
        }

        var times = newObj.time;
        newObj['startTime'] = times && times.split('至')[0]
        newObj['endTime'] = times && times.split('至')[1] || '';
        //查询条件参数获取 end
        var param = null;
        param = {
            query:'y',
            selectids:newSelectids || ''
        }
        param = $.extend({}, param, newObj);
        
        // console.log(param)
        this.downFile(param,url);//下载表格
    },
    
    init:function(elem,data,param) {
        this.binds();//IE注入bind
        var option = {//导出默认配置
            
        };
        option = $.extend({}, option, param);
        this.exportParam = option;
        this.render(elem,data);
    },
    render:function(elem,data) {
        var that = this;
        elem.html(template.render(search_view, data));
        placeholder.init();
        this.reqCompany();
    },
    showInfo:function(param,url) {
        request.post(url,{key:param[0]},function(res){
            console.log(res)
        })
    },
    downFile:function(params,url) {//下载文件
        var tpl = renders({
                <form class="f-dn" method="post" target="_blank" action="<%url%>">
                    <%each params%>
                        <input type="hidden" name="<% $index %>" value="<%$value%>">
                    <%/each%>
                </form>
        })
        console.log(params)
        var form = $(template.render(tpl, {url:Nui.domain+url+request.config('ext'), params:params})).appendTo('body');
        form.submit();
        form.remove();
    }
})